package com.setup.trac.controller;

import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractWizardFormController;

import com.setup.trac.dao.DAOService;
import com.setup.trac.pojo.Progetti;
import com.setup.trac.pojo.Utenti;
import com.setup.trac.pojo.comparator.UsersOrderByCognomeNome;
import com.setup.trac.pojo.condition.FindUtentiByIds;
import com.setup.trac.service.MailSenderService;
import com.setup.trac.service.SearchService;

public class CreateProjectController extends AbstractWizardFormController {

	private SearchService searchService;
	private DAOService daoService;
	private MailSenderService mailSenderService;

	@Override
	protected ModelAndView processFinish(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		Progetti p = (Progetti) command;
		String[] ids = request.getParameterValues("utentiSelezionati");
		Utenti[] users = searchService.find(new Utenti[0], new FindUtentiByIds(ids), Utenti.class);
		CollectionUtils.addAll(p.getUtentis(), users);
		getDaoService().insert(p);
		ModelAndView mav = new ModelAndView("adminConsole");
		return mav;
	}


	public SearchService getSearchService() {
		return searchService;
	}

	public void setSearchService(SearchService searchService) {
		this.searchService = searchService;
	}

	public DAOService getDaoService() {
		return daoService;
	}

	public void setDaoService(DAOService daoService) {
		this.daoService = daoService;
	}


	@Override
	protected void validatePage(Object command, Errors errors, int page,
			boolean finish) {
		System.out.println("CreateProjectController.validatePage()");
		Progetti p = (Progetti) command;
		if(finish){
			
		}else{
			switch(page){
			case 0:
				if(p.getDescrizione()==null || p.getDescrizione().trim().equals("")){
					errors.rejectValue("descrizione", "", "Campo obbligatorio");
				}
				break;
			case 1:
				
				break;
			}
		}
	}


	@Override
	protected void postProcessPage(HttpServletRequest request, Object command,
			Errors errors, int page) throws Exception {
		if(!errors.hasErrors()){
			Utenti[] users = getSearchService().find(new Utenti[0], Utenti.class);
			Arrays.sort(users, new UsersOrderByCognomeNome());
			request.setAttribute("listaUtenti", users);
		}
		
	}


	public MailSenderService getMailSenderService() {
		return mailSenderService;
	}


	public void setMailSenderService(MailSenderService mailSenderService) {
		this.mailSenderService = mailSenderService;
	}


	
}
